<?php

namespace app\xinrong\controller;

use app\xinrong\model\XinrongCostModel;
use app\xinrong\model\XinrongCostTypeModel;
use app\xinrong\model\XinrongMaterialModel;
use app\xinrong\model\XinrongProductModel;
use cmf\controller\AdminBaseController;

class MaterialController extends AdminBaseController
{
    public function index()
    {
        $where = [
            'status' => 1
        ];
        $uid = cmf_get_current_admin_id();
        if ($uid != 1) {
            $users = implode(',', getUsersForRole($uid));
            $where['manager'] = ['in', $users];
        }
        if (input('keyword')) {
            $keyword = input('keyword');
            $where['name'] = ['like', "%$keyword%"];
        }
        $xinrongMaterialModel = new XinrongMaterialModel();
        $lists = $xinrongMaterialModel
            ->alias('material')
            ->join('__USER__ user','user.id = material.manager')
            ->where($where)
            ->field('material.*,user.user_nickname')
            ->order('id desc')
            ->paginate();

        $lists->appends(input());

        $this->assign('lists', $lists);
        $this->assign('page', $lists->render());
        return $this->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $arrData = $this->request->post();
            $arrData['manager'] = cmf_get_current_admin_id();

            $xinrongMaterialModel = new XinrongMaterialModel();
            $xinrongMaterialModel->allowField(true)->save($arrData);
            if (isset($arrData['cost'][$arrData['type']])) {
                $id = $xinrongMaterialModel->id;
                $costs = [];
                $cost = 0;
                foreach ($arrData['cost'][$arrData['type']] as $key => $val) {
                    $costs[] = [
                        'cost' => $val,
                        'cid' => $key,
                        'tid' => $arrData['type'],
                        'pid' => $id,
                    ];
                    $cost += $val;
                }
                if ($costs) {
                    $xinrongCostModel = new XinrongCostModel();
                    $xinrongCostModel->saveAll($costs);
                    $xinrongMaterialModel->where([
                        'id' => $id
                    ])->setField('cost', $cost);
                }
            }
            $this->success('添加成功！', url('index'));
        }

        $xinrongCostTypeModel = new XinrongCostTypeModel();
        $types = $xinrongCostTypeModel
            ->where([
                'cid' => ['in', '1,2']
            ])
            ->select();

        $this->assign('types', $types);
        return $this->fetch();
    }

    public function edit()
    {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $xinrongMaterialModel = new XinrongMaterialModel();
        $result = $xinrongMaterialModel
            ->with(['costs' =>function($query){$query->where([
                'tid' => ['in','1,2']
            ]);}])->find($id);

        if ($this->request->isPost()) {
            $arrData = $this->request->post();

            $xinrongMaterialModel = new XinrongMaterialModel();
            $xinrongMaterialModel->allowField(true)->save($arrData,['id' => $id]);
            if (isset($arrData['cost'][$result['type']])) {
                $cost = 0;
                $xinrongCostModel = new XinrongCostModel();
                foreach ($arrData['cost'][$result['type']] as $key => $val) {
                    $flag = true;
                    foreach ($result['costs'] as $costs) {
                        if($costs['cid'] == $key) {
                            if($costs['cost'] != $val) {
                                $xinrongCostModel->where([
                                    'id' => $costs['id']
                                ])->setField('cost',$val);
                            }
                            $flag = false;
                            break;
                        }
                    }
                    if($flag) {
                        $xinrongCostModel->save([
                            'cost' => $val,
                            'cid' => $key,
                            'tid' => $result['type'],
                            'pid' => $id,
                        ]);
                    }
                    $cost += $val;
                }
                if ($cost != $result['cost']) {
                    $xinrongMaterialModel->where([
                        'id' => $id
                    ])->setField('cost', $cost);
                }
            }
            $this->success('保存成功！', url('index'));
        }

        $xinrongCostTypeModel = new XinrongCostTypeModel();
        $types = $xinrongCostTypeModel
            ->where([
                'cid' => ['in', '1,2']
            ])
            ->select();

        foreach ($types as $type) {
            $type->setAttr('cost',0);
            foreach ($result['costs'] as $cost) {
                if($cost['cid'] == $type['id']) {
                    $type->setAttr('cost',$cost['cost']);
                    break;
                }
            }
        }

        $this->assign('types', $types);
        $this->assign('result', $result);
        return $this->fetch();
    }

    /**
     * 复选
     * @return mixed
     */
    public function check()
    {
        $ids = $this->request->param('id', '');
        $pid = $this->request->param('pid', 0,'intval');
        $ids = explode(',', $ids);

        $xinrongMaterialModel = new XinrongMaterialModel();
        $lists = $xinrongMaterialModel
            ->alias('material')
            ->join('__USER__ user','material.manager = user.id')
            ->field('material.*,user.user_nickname')
            ->where([
                'status' => 1
            ])
            ->whereOr(function ($query) use ($ids,$pid){
                $query->where([
                    'status' => 2,
                    'material.id' => ['in',$ids],
                    'to_id' => $pid,
                    'to_type' => 1
                ]);
            })
            ->select();

        $this->assign('lists', $lists);
        $this->assign('ids', $ids);
        return $this->fetch();
    }

    public function restore() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $xinrongMaterialModel = new XinrongMaterialModel();
        $info = $xinrongMaterialModel->save([
            'status' => 0
        ],[
            'id' => $id
        ]);

        $xinrongProductModel = new XinrongProductModel();
        $xinrongProductModel->save([
            'status' => 1
        ],[
            'status' => 2,
            'to_id' => $id,
            'to_type' => 1
        ]);
        $this->success('还原成功！');
    }

    public function conversion() {
        $id = $this->request->param('id',0,'intval');
        if(!$id) {
            $this->error('访问错误！');
        }
        $xinrongMaterialModel = new XinrongMaterialModel();
        $result = $xinrongMaterialModel->find($id);
        if(!$result) {
            $this->error('访问错误！');
        }
        if($this->request->isPost()) {
            $arrData = $this->request->post('');
            $xinrongMaterialModel->allowField(true)->save($arrData,['id' => $id]);

            $xinrongProductModel = new XinrongProductModel();
            $flag = $xinrongProductModel->save([
                'name' => $result['name'],
                'reg_time' => $result['reg_time'],
                'cost' => $result['cost'],
                'manager' => cmf_get_current_admin_id(),
                'type' => $result['type'],
                'status' => 1,
                'price' => $arrData['price'],
                'area' => $arrData['area'],
                'end_time' => $arrData['end_time'],
                'registered_capital' => $arrData['registered_capital'],
                'corporation' => $arrData['corporation'],
                'score' => 2,
            ]);
            if($flag === false) {
                $this->error('转化失败！');
            }
            $xinrongMaterialModel->save([
                'status' => 2,
                'to_id' => $xinrongProductModel->id,
                'to_type' => 1
            ],[
                'id' => $id,
                'status' => 1
            ]);
            $this->success('转化成功！',url('product/index'));
        }

        $this->assign('result',$result);
        return $this->fetch();
    }
}